package com.darren.euc.service.impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.darren.euc.dao.PlaceDao;
import com.darren.euc.dao.SpaceDao;
import com.darren.euc.dao.SystemDao;
import com.darren.euc.entity.City;
import com.darren.euc.entity.Province;
import com.darren.euc.entity.SpaceStatus;
import com.darren.euc.entity.SystemParameter;
import com.darren.euc.service.SystemService;
import com.darren.euc.util.CacheUtil;
import com.darren.euc.util.Constant;
import com.darren.euc.util.PropertyHelper;

import net.sf.json.JSONObject;


@Service
public class SystemServiceImpl implements SystemService {
	
	private static final Logger log = Logger.getLogger(SystemServiceImpl.class);
	
	@Autowired
    private SystemDao systemDao;
	
	@Autowired
    private PlaceDao placeDao;
	
	@Autowired
    private SpaceDao spaceDao;
	

	@Override
	public List<SystemParameter> getAll() {
		return systemDao.getAll();
	}
	
	private List<SystemParameter> paramsList;
	
	@SuppressWarnings("unchecked")
	public List<SystemParameter> initalSystemParameter() {
		log.info("initial system parameter cache.....");
		CacheUtil cacheUtil = CacheUtil.getInstance();
		paramsList = (List<SystemParameter>)cacheUtil.get(Constant.CACHE_NAME_MEMBER, Constant.CACHE_SYSTEM_PARAMS);
		if(paramsList == null){
			paramsList = systemDao.getAll();
			if(paramsList != null && paramsList.size() > 0){
				cacheUtil.remove(Constant.CACHE_NAME_MEMBER, Constant.CACHE_SYSTEM_PARAMS);
			}
			cacheUtil.put(Constant.CACHE_NAME_MEMBER,Constant.CACHE_SYSTEM_PARAMS, paramsList);
		}
		return paramsList;
	}
	

	public void refresh() {
		log.info("refresh system parameter cache.....");
		CacheUtil cacheUtil = CacheUtil.getInstance();
		cacheUtil.remove(Constant.CACHE_NAME_MEMBER, Constant.CACHE_SYSTEM_PARAMS);
		initalSystemParameter();
	}
	
	
	public String getScreenToken() {
		log.info("initial system parameter cache.....");
		CacheUtil cacheUtil = CacheUtil.getInstance();
		String screenToken = (String)cacheUtil.get(Constant.CACHE_NAME_MEMBER, Constant.CACHE_SCREEN_TOKEN);
		if(screenToken == null){
			BufferedReader bufferedReader = null;
			HttpURLConnection connection = null;
			DataOutputStream out = null;
			InputStream inputStream = null;
			InputStreamReader inputStreamReader = null;
			String requestResult = "";
			try {
				URL loginUrl = new URL(PropertyHelper.getScreenTokenURL());				
				connection = (HttpURLConnection) loginUrl.openConnection();
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setUseCaches(false);
				connection.setInstanceFollowRedirects(false);
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				connection.connect();
				out = new DataOutputStream(connection.getOutputStream());
				String content = URLEncoder.encode("user_id", "UTF-8") + "=" + URLEncoder.encode("123456", "UTF-8");
				out.writeBytes(content);
				out.flush();
				out.close();
				inputStream = connection.getInputStream();
				inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
				bufferedReader = new BufferedReader(inputStreamReader);

				// 遍历得到的数据
				for (String line = null; (line = bufferedReader.readLine()) != null;) {
					requestResult += line;					
				}
				System.out.println(requestResult);
				JSONObject responseJson = JSONObject.fromObject(requestResult);
				screenToken = responseJson.getString("token");
				connection.disconnect();
			} catch (IOException e) {
				log.info("请求电子屏Token失败！");
				log.error(e.getMessage(),e);				
			}finally{
				
				try {
					if (bufferedReader != null) {
						bufferedReader.close();
					}
					if(connection != null ){
						connection.disconnect();
					}
					
					if(out != null){
						out.close();
					}
					
					if(inputStream != null){
						inputStream.close();
					}
					if(inputStreamReader != null){
						inputStreamReader.close();
					}
				} catch (IOException e) {
					log.info("关闭电子屏Token请求资源失败！");
					log.error(e.getMessage(),e);
				}
			}
			cacheUtil.put(Constant.CACHE_NAME_MEMBER,Constant.CACHE_SCREEN_TOKEN, screenToken);
		}
		return screenToken;
	}
	
	
	public void refreshScreenToken() {
		log.info("refresh system parameter cache.....");
		CacheUtil cacheUtil = CacheUtil.getInstance();
		cacheUtil.remove(Constant.CACHE_NAME_MEMBER, Constant.CACHE_SCREEN_TOKEN);
		getScreenToken();
	}
	
	
	public List<Province> getAllProvinces(){
		return placeDao.getAllProvinces();
	}
	
	public List<City> getAllCity(){
		return placeDao.getAllCity();
	}
	
	public List<SpaceStatus> getAllSpaceStatus(){
		return spaceDao.getAllSpaceStatus();
	}
	
	
	/**
	 * 生成个人消息
	 */
	public void generateMessage(){
		systemDao.generateMessage();	
    }

}